# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, time
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "陪伴终身还返还的意外保险产品组合"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 71)],
                # 保障期限
                "days": ["zs"],
                # 保障人数
                "people_count": ["1"],
                # 保额
                "money": ["100000"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 交费间隔
                "interval": ["10", "20"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["days"], plan[k]["people_count"], plan[k]["money"],
                             plan[k]["payType"], plan[k]["interval"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        params = '''
        appName: 
        appSex: M
        appidType: A
        appidNo: 
        appBirthday: 1993-02-02
        appPhone: 
        appPro: 110000
        appCity: 110100
        appAddress: 
        appEmail: 
        name: 
        sex: M
        idType: A
        idNo: 
        birthday: 1993-02-02
        phone: 
        pro: 110000
        city: 110100
        address: 
        email: 
        source: CUS000000046
        planCode: P000000865
        planAmnt: 100000
        polTerm: 106
        poltermType: A
        payPeriod: 10
        payIntv: 12
        relation: 0
        validate: 
        '''
        data = Helper.perfectJson(params)
        data["appBirthday"] = "{0}-01-01".format(str(int(2020 - int(dt["year"]))))
        data["birthday"] = "{0}-01-01".format(str(int(2020 - int(dt["year"]))))
        data["payIntv"] = "12" if dt["payType"] == "年交" else "1"
        data["payPeriod"] = dt["interval"]
        data["planCode"] = "P000000865" if dt["interval"] == "20" else "P000000861"
        print(data)

        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and r.json()["success"]:
            price = Helper.decimalParse(r.json()["msg"])
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price

            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格信息更新失败:%d*/" % dt["id"])
